<?php
namespace App\Models\Scripts;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class v32595ace772e67e603f3f0f3c58fb6a9 extends Sysupdate
{
    protected $version_id ='assign_log';

    private $table_name = 'assign_log';
    private $returnData = array('code'=>0,'message'=>'执行成功');

    public function upgrade()
    {
        $r_data = $this->_step_1();
        if(!$r_data){
            return $r_data;
        }
        $r_data = $this->_step_2();
        if(!$r_data){
            return $r_data;
        }
        return $this->returnData;
    }

    private function _step_1()
    {
        $sql = "alter table ".$this->table_name." add assign_uid int(11) DEFAULT NULL COMMENT '转移人';";
        DB::statement($sql);
        $sql = "alter table ".$this->table_name." add assign_touid int(11) DEFAULT NULL COMMENT '接收人';";
        DB::statement($sql);
        $sql = "alter table ".$this->table_name." add operation_uid int(11) DEFAULT NULL COMMENT '操作人';";
        DB::statement($sql);
        return $this->returnData;
    }

    private function _step_2()
    {
        $sql = "SELECT a.*,au.id as auid,au.name as auname,auc.id as aucid,auc.name as aucname FROM assign_log as a ".
            "LEFT JOIN admin_users as au ON a.assign_name=CONVERT(au.name USING utf8) COLLATE utf8_unicode_ci ".
            "LEFT JOIN admin_users as auc ON a.assign_admin=CONVERT(auc.name USING utf8) COLLATE utf8_unicode_ci ";
        $res = DB::select($sql);
        $res = json_decode(json_encode($res),true);
        $fail_list = [];
        foreach ($res as $key=>$value){
            $fields = array(
                'assign_uid' => $value['aucid'],
                'assign_touid' => $value['auid'],
                'operation_uid' => $value['aucid']
            );
            $flag = DB::table($this->table_name)->where('id',$value['id'])->update($fields);
            if($flag){
                continue;
            }
            $fail_list[] = $value['id'];
        }

        if(count($fail_list)>0){
            $this->returnData['code'] = 99;
            $this->returnData['message'] ='部分id同步失败';
            $this->returnData['list'] = json_encode($fail_list);
            return $this->returnData;
        }
        $this->returnData['message'] ='同步成功';
        return $this->returnData;
    }
}
